package com.Xht.www.servlet;

//后端响应查询用户信息的请求

import com.Xht.www.po.UserInfoPO;
import com.Xht.www.service.User;
import com.Xht.www.serviceImpl.UserImpl;
import com.Xht.www.serviceImpl.UserImpl;
import com.google.gson.Gson;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/getUserInfo")
public class GetUserInfoServlet extends HttpServlet {

    private final User userService = new UserImpl(); // 使用接口编程

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        if (username == null || username.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing username parameter");
            return;
        }

        UserInfoPO user = userService.getUserByUsername(username); // 调用接口方法

        if (user == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            try (PrintWriter out = response.getWriter()) {
                out.write("{\"success\":false,\"message\":\"用户不存在\"}");
            }
            return;
        }

        Gson gson = new Gson();
        try (PrintWriter out = response.getWriter()) {
            out.write(gson.toJson(user));
        }
    }
}


